package com.airsystem.pos.bengkel.controller;

import java.awt.event.ItemEvent;
import java.util.List;
import java.util.Vector;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

import com.airsystem.pos.bengkel.component.TableFrame;
import com.airsystem.pos.bengkel.entity.DetailKendaraan;
import com.airsystem.pos.bengkel.entity.DetailPelanggan;
import com.airsystem.pos.bengkel.entity.Kendaraan;
import com.airsystem.pos.bengkel.entity.Pelanggan;
import com.airsystem.pos.bengkel.interfaces.IMaster;
import com.airsystem.pos.bengkel.interfaces.ISystem;
import com.airsystem.pos.bengkel.interfaces.ITable;
import com.airsystem.pos.bengkel.model.MasterCustomerModel;
import com.airsystem.pos.bengkel.service.KendaraanServices;
import com.airsystem.pos.bengkel.service.PelangganServices;
import com.airsystem.pos.bengkel.view.dialog.MasterCustomerDialog;

/**
 * @author Budi Oktaviyan <budi.oktaviyan@icloud.com>
 */
public class MasterCustomerController extends MasterCustomerModel implements IMaster, ITable, ISystem {
	private static final Logger LOG = Logger.getLogger(MasterCustomerController.class.getSimpleName());

	private String nama, merk, subMerk, tahun, nopol, norangka, nomesin, ID, FK;

	private PelangganServices pelangganServices = new PelangganServices();

	private KendaraanServices kendaraanServices = new KendaraanServices();

	public MasterCustomerController() {
		super();
	}

	public void setup() {
		saveButton.setVisible(true);
		updateButton.setVisible(false);
		deleteButton.setVisible(false);

		saveButton.setEnabled(false);
	}

	public void search() {
		dialogMasterCustomer = new MasterCustomerDialog();

		try {
			if (dialogMasterCustomer.getNama() == null
			||	dialogMasterCustomer.getPelanggans().size() == 0) {
				cancel();
			} else {
				idField.setText(dialogMasterCustomer.getId());
				namaField.setText(dialogMasterCustomer.getNama());

				TableFrame.deleteTable(tableCustomer, tableModel);
				for (DetailPelanggan data : dialogMasterCustomer.getPelanggans()) {
					tableModel.addRow(new String[] { data.getDetail_kendaraan().getKendaraan().getMerk(),
													 data.getDetail_kendaraan().getSub_merk(),
													 data.getTahun(), 
													 data.getNopol(), 
													 data.getNorangka(), 
													 data.getNomesin(), 
													 "OLD", 
													 String.valueOf(data.getId()) });
				}
				tableCustomer.setModel(tableModel);

				saveButton.setVisible(false);
				updateButton.setVisible(true);
				deleteButton.setVisible(true);
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
	}

	public void get() {
		ID = idField.getText();
		FK = fkField.getText();
		nama = namaField.getText();
		tahun = tahunField.getText();
		nopol = nopolField.getText();
		norangka = norangkaField.getText();
		nomesin = nomesinField.getText();

		if (merkkendaraanCombo.getSelectedItem() != null) {
			merk = merkkendaraanCombo.getSelectedItem().toString();
		}
	}

	public void reset() {
		fkField.setText("");
		tahunField.setText("");
		nopolField.setText("");
		norangkaField.setText("");
		nomesinField.setText("");

		if (merkkendaraanCombo.getSelectedItem() != null
		&&  submerkkendaraanCombo.getSelectedItem() != null) {
			merkkendaraanCombo.setSelectedIndex(0);
			submerkkendaraanCombo.setSelectedIndex(0);
		}
	}

	public void save() {
		try {
			get();

			if (nama.isEmpty()) {
				JOptionPane.showMessageDialog(MasterCustomerController.this, "Data kosong!", "Pesan", JOptionPane.WARNING_MESSAGE);
			} else {
				Pelanggan pelanggan = new Pelanggan();
				pelanggan.setNama(nama);
				pelangganServices.saveOrUpdate(pelanggan);

				for (int i = 0; i < tableModel.getRowCount(); i++) {
					Kendaraan kendaraan = new Kendaraan();
					kendaraan.setMerk(tableCustomer.getValueAt(i, 0).toString());

					DetailKendaraan detailKendaraan = new DetailKendaraan();
					detailKendaraan.setSub_merk(tableCustomer.getValueAt(i, 1).toString());

					DetailPelanggan detailPelanggan = new DetailPelanggan();
					detailPelanggan.setPelanggan(pelanggan);
					detailPelanggan.setDetail_kendaraan(detailKendaraan);
					detailPelanggan.setTahun(tableCustomer.getValueAt(i, 2).toString());
					detailPelanggan.setNopol(tableCustomer.getValueAt(i, 3).toString());
					detailPelanggan.setNorangka(tableCustomer.getValueAt(i, 4).toString());
					detailPelanggan.setNomesin(tableCustomer.getValueAt(i, 5).toString());

					pelangganServices.saveOrUpdate(detailPelanggan);
				}

				JOptionPane.showMessageDialog(MasterCustomerController.this, "Simpan data sukses", "Pesan", JOptionPane.INFORMATION_MESSAGE);
				cancel();
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			JOptionPane.showMessageDialog(MasterCustomerController.this, "Simpan data gagal!", "Pesan", JOptionPane.ERROR_MESSAGE);
		}
	}

	public void update() {
		try {
			get();
			getSubField();

			if (saveButton.isVisible()) {
				/* Save data state */
				edit();
			} else {
				if (nama.isEmpty()) {
					JOptionPane.showMessageDialog(MasterCustomerController.this, "Data kosong!", "Pesan", JOptionPane.WARNING_MESSAGE);
				} else {
					/* Update data state */
					Pelanggan pelanggan = new Pelanggan();
					pelanggan.setId(Long.valueOf(ID));
					pelanggan.setNama(nama);
					pelangganServices.saveOrUpdate(pelanggan);

					if (!FK.isEmpty()) {
						/* Update data per item */
						Kendaraan kendaraan = new Kendaraan();
						kendaraan.setMerk(merk);

						DetailKendaraan detailKendaraan = new DetailKendaraan();
						detailKendaraan.setSub_merk(subMerk);

						DetailPelanggan detailPelanggan = new DetailPelanggan();
						detailPelanggan.setPelanggan(pelanggan);
						detailPelanggan.setDetail_kendaraan(detailKendaraan);
						detailPelanggan.setId(Long.valueOf(fkField.getText()));
						detailPelanggan.setTahun(tahun);
						detailPelanggan.setNopol(nopol);
						detailPelanggan.setNorangka(norangka);
						detailPelanggan.setNomesin(nomesin);

						pelangganServices.saveOrUpdate(detailPelanggan);
						edit();
					} else {
						/* Update all new data */
						for (int i = 0; i < tableCustomer.getRowCount(); i++) {
							if ("NEW".equalsIgnoreCase(tableCustomer.getValueAt(i, 6).toString())) {
								Kendaraan kendaraan = new Kendaraan();
								kendaraan.setMerk(tableCustomer.getValueAt(i, 0).toString());

								DetailKendaraan detailKendaraan = new DetailKendaraan();
								detailKendaraan.setSub_merk(tableCustomer.getValueAt(i, 1).toString());

								DetailPelanggan detailPelanggan = new DetailPelanggan();
								detailPelanggan.setPelanggan(pelanggan);
								detailPelanggan.setDetail_kendaraan(detailKendaraan);
								detailPelanggan.setTahun(tableCustomer.getValueAt(i, 2).toString());
								detailPelanggan.setNopol(tableCustomer.getValueAt(i, 3).toString());
								detailPelanggan.setNorangka(tableCustomer.getValueAt(i, 4).toString());
								detailPelanggan.setNomesin(tableCustomer.getValueAt(i, 5).toString());

								pelangganServices.saveOrUpdate(detailPelanggan);
							}
						}

						JOptionPane.showMessageDialog(MasterCustomerController.this, "Ubah data sukses", "Pesan", JOptionPane.INFORMATION_MESSAGE);
						cancel();
					}
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			JOptionPane.showMessageDialog(MasterCustomerController.this, "Ubah data gagal!", "Pesan", JOptionPane.ERROR_MESSAGE);
		}
	}

	public void delete() {
		try {
			get();
			getSubField();

			if (saveButton.isVisible()) {
				/* Save data state */
				remove();
			} else {
				if (nama.isEmpty()) {
					JOptionPane.showMessageDialog(MasterCustomerController.this, "Data kosong!", "Pesan", JOptionPane.WARNING_MESSAGE);
				} else {
					/* Delete data state */
					Pelanggan pelanggan = new Pelanggan();
					pelanggan.setId(Long.valueOf(ID));
					pelanggan.setNama(nama);

					if (!FK.isEmpty()) {
						/* Delete data per item */
						Kendaraan kendaraan = new Kendaraan();
						kendaraan.setMerk(merk);

						DetailKendaraan detailKendaraan = new DetailKendaraan();
						detailKendaraan.setSub_merk(subMerk);

						DetailPelanggan detailPelanggan = new DetailPelanggan();
						detailPelanggan.setPelanggan(pelanggan);
						detailPelanggan.setDetail_kendaraan(detailKendaraan);
						detailPelanggan.setId(Long.valueOf(fkField.getText()));
						detailPelanggan.setTahun(tahun);
						detailPelanggan.setNopol(nopol);
						detailPelanggan.setNorangka(norangka);
						detailPelanggan.setNomesin(nomesin);

						pelangganServices.delete(detailPelanggan);
						remove();
					} else {
						/* Delete all data */
						pelangganServices.delete(pelanggan);

						JOptionPane.showMessageDialog(MasterCustomerController.this, "Hapus data sukses", "Pesan", JOptionPane.INFORMATION_MESSAGE);
						cancel();
					}
				}
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			JOptionPane.showMessageDialog(MasterCustomerController.this, "Hapus data gagal!", "Pesan", JOptionPane.ERROR_MESSAGE);
		}
	}

	public void cancel() {
		TableFrame.deleteTable(tableCustomer, tableModel);
		idField.setText("");
		namaField.setText("");
		reset();
		setup();
	}

	public void init() {
		tahunField.setText(tableCustomer.getValueAt(row, 2).toString());
		nopolField.setText(tableCustomer.getValueAt(row, 3).toString());
		norangkaField.setText(tableCustomer.getValueAt(row, 4).toString());
		nomesinField.setText(tableCustomer.getValueAt(row, 5).toString());

		if (merkkendaraanCombo.getSelectedItem() != null
		&&  submerkkendaraanCombo.getSelectedItem() != null) {
			merkkendaraanCombo.setSelectedItem(tableCustomer.getValueAt(row, 0).toString());
			submerkkendaraanCombo.setSelectedItem(tableCustomer.getValueAt(row, 1).toString());
		}

		if (tableCustomer.getValueAt(row, 7) != null) {
			fkField.setText(tableCustomer.getValueAt(row, 7).toString());
		}

		if (saveButton.isVisible()) {
			updateButton.setVisible(true);
			deleteButton.setVisible(true);
		}
	}

	public void add() {
		get();
		getSubField();

		if (tahun.isEmpty() || nopol.isEmpty() || norangka.isEmpty() || nomesin.isEmpty()) {
			JOptionPane.showMessageDialog(MasterCustomerController.this, "Data kosong!", "Pesan", JOptionPane.WARNING_MESSAGE);
		} else {
			Vector<String> vector = new Vector<String>();
			vector.add(merk);
			vector.add(subMerk);
			vector.add(tahun);
			vector.add(nopol);
			vector.add(norangka);
			vector.add(nomesin);
			vector.add("NEW");

			boolean isExist = false;
			for (int i = 0; i < tableCustomer.getRowCount(); i++) {
				if (subMerk != null
				&&  subMerk.equalsIgnoreCase(tableCustomer.getValueAt(i, 1).toString())) {
					isExist = true;
					break;
				}
			}

			if (!isExist) {
				tableModel.addRow(vector);
				tableCustomer.setModel(tableModel);

				if (saveButton.isVisible()) {
					saveButton.setEnabled(true);
				}
			} else {
				JOptionPane.showMessageDialog(MasterCustomerController.this, "Data sudah ada!", "Pesan", JOptionPane.WARNING_MESSAGE);
			}

			reset();
		}
	}

	public void edit() {
		get();
		getSubField();

		if (tahun.isEmpty() || nopol.isEmpty() || norangka.isEmpty() || nomesin.isEmpty()) {
			JOptionPane.showMessageDialog(MasterCustomerController.this, "Data kosong!", "Pesan", JOptionPane.WARNING_MESSAGE);
		} else {
			Vector<String> vector = new Vector<String>();
			vector.add(merk);
			vector.add(subMerk);
			vector.add(tahun);
			vector.add(nopol);
			vector.add(norangka);
			vector.add(nomesin);
			vector.add("OLD");
			vector.add(FK);

			tableModel.removeRow(row);
			tableModel.addRow(vector);
			tableCustomer.setModel(tableModel);

			if (saveButton.isVisible()) {
				saveButton.setEnabled(true);
			}

			reset();
		}
	}

	public void remove() {
		tableModel.removeRow(row);
		reset();

		if (tableCustomer.getRowCount() == 0) {
			cancel();
		}
	}

	public void load() {
		try {
			List<Kendaraan> kendaraans = kendaraanServices.select();
			for (Kendaraan kendaraan : kendaraans) {
				merkkendaraanCombo.addItem(kendaraan.getMerk());
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			JOptionPane.showMessageDialog(MasterCustomerController.this, "Load data gagal!", "Pesan", JOptionPane.ERROR_MESSAGE);
		}
	}

	protected void loadSubField(ItemEvent evt) {
		if (evt.getStateChange() == ItemEvent.SELECTED) {
			try {
				get();
				submerkkendaraanCombo.removeAllItems();

				List<DetailKendaraan> detailKendaraans = kendaraanServices.select(merk);
				for (DetailKendaraan detailKendaraan : detailKendaraans) {
					submerkkendaraanCombo.addItem(detailKendaraan.getSub_merk());
				}
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				JOptionPane.showMessageDialog(MasterCustomerController.this, "Load data gagal!", "Pesan", JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	private void getSubField() {
		if (submerkkendaraanCombo.getSelectedItem() != null) {
			subMerk = submerkkendaraanCombo.getSelectedItem().toString();
		}
	}
}